package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.VideoScore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author anshuai
 * @create 2021-02-26 16:29
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "tanhua-video",consumerGroup = "tanhua-video-group")
public class VideoScoreListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String message) {

        log.info("====收到视频消息，供大数据推荐系统使用【开始】 topic:{}, message:{}", "tanhua-video", message);

        //1.还原成Map
        Map map = JSON.parseObject(message, Map.class);

        //2. 获取参数
        long userId = Long.parseLong(map.get("userId").toString());
        long videoId = Long.parseLong(map.get("videoId").toString());
        Integer type = (Integer) map.get("type");

        //3. 封装对象
        VideoScore videoScore = new VideoScore();
        videoScore.setId(ObjectId.get());
        videoScore.setUserId(userId);
        videoScore.setVideoId(videoId);
        videoScore.setDate(System.currentTimeMillis());
        switch (type) {
            case 1:
                videoScore.setScore(20d);
                break;
            case 2:
                videoScore.setScore(5d);
                break;
            case 3:
                videoScore.setScore(-5d);
                break;
            case 4:
                videoScore.setScore(10d);
                break;
            default:
        }

        //4. 保存到MongoDB
        mongoTemplate.save(videoScore);

        log.info("====收到视频消息，供大数据推荐系统使用【完成】");
    }
}
